package com.learn.annotate;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Annotation在反射函数中的使用示例
 */
public class AnnotationTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException,
                                                          IllegalAccessException {
        PersonT personT = new PersonT();
        // 获取PersonT的Class实例
        Class<PersonT> c = PersonT.class;
        // 获取 somebody() 方法的Method实例
        Method mSomeBody = c.getMethod("somebody", new Class[]{String.class,int.class});
        mSomeBody.invoke(personT,new Object[]{"lily",18});

        iteratorAnnotations(mSomeBody);

       /* // 获取 somebody() 方法的Method实例
        Method mEmpty = c.getMethod("empty", new Class[]{});
        // 执行该方法
        mEmpty.invoke(personT, new Object[]{});
        iteratorAnnotations(mEmpty);*/
    }

    public static void iteratorAnnotations(Method method){
        System.out.println("方法名："+method.getName());
        // 判断 somebody() 方法是否包含AAAnnotation注解
        if(method.isAnnotationPresent(AAAnnotation.class)){
            // 获取该方法的AAAnnotation注解实例
            AAAnnotation aaAnnotation = method.getAnnotation(AAAnnotation.class);
            // 获取 myAnnotation的值，并打印出来
            String[] values = aaAnnotation.value();
            for(String str:values){
                System.out.println(">iteratorAnnotations>判断:"+str);
            }
            System.out.println();
        }
        // 获取方法上的所有注解，并打印出来
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation:annotations){
            System.out.println(">iteratorAnnotations>获取方法上的所有注解:"+annotation);
        }
    }
}

@Retention(RetentionPolicy.RUNTIME)
@interface AAAnnotation{
    String[] value() default "unknown";
}
/**
 * PersonT类。它会使用AAAnnotation注解。
 */
class PersonT {
    @AAAnnotation
    @Deprecated
    public void empty(){
        System.out.println("empty");
    }
    @AAAnnotation(value = {"girl","body"})
    public void somebody(String name, int age){
        System.out.println("somebody:"+name+","+age);
    }
}
